package pe.edu.upc.dai.grupo4.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import pe.edu.upc.dai.grupo4.model.Banco;
import pe.edu.upc.dai.grupo4.utils.ConnectionUtils;
import pe.edu.upc.dai.grupo4.utils.DaoException;

/**
 *
 * @author Tito Luyo Murata
 */
public class BancoDaoImpl implements BancoDao {

    public Banco selectPorCodBanco(int codBanco) {
        Banco result = null;
        Connection connection = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            connection = ConnectionUtils.getConnection();
            st = connection.prepareStatement("{call dbo.usp_Bancos_SEL_x_codBanco(?)}");
            st.setInt(1, codBanco);
            rs = st.executeQuery();
            if (rs.next()) {
                result = this.getData(rs);
            }
        } catch (SQLException e) {
            throw new DaoException(e);
        } finally {
            ConnectionUtils.closeResultSet(rs);
            ConnectionUtils.closeStatement(st);
            ConnectionUtils.closeConnection(connection);
        }
        return result;
    }

    public List<Banco> select() {
        List<Banco> result = new ArrayList<Banco>();
        Connection connection = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            connection = ConnectionUtils.getConnection();
            st = connection.prepareStatement("{call dbo.usp_Bancos_SEL}");
            rs = st.executeQuery();
            while (rs.next()) {
                result.add(this.getData(rs));
            }
        } catch (SQLException e) {
            throw new DaoException(e);
        } finally {
            ConnectionUtils.closeResultSet(rs);
            ConnectionUtils.closeStatement(st);
            ConnectionUtils.closeConnection(connection);
        }
        return result;
    }

    private Banco getData(ResultSet rs) throws SQLException {
        Banco result = null;
        EstadoDao estadoDao = new EstadoDaoImpl();
        result = new Banco(
                rs.getInt("CodBanco"),
                rs.getString("NombreBanco"),
                estadoDao.selectPorBanco(rs.getString("Estado"))
                );
        return result;
    }
}

